<template>
  <el-dialog
    title="奖金发起"
    :close-on-click-modal="false"
    :visible.sync="visible"
    fullscreen
    :show-close="false"
    @close="close"
  >
    <el-form
      :model="dataForm"
      :key="isRef"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="130px"
      style="height: 85vh; overflow-y: auto"
    >
      <div class="boxsty" style="margin-bottom: 30px">
        <el-row>
          <el-col :span="20">
            <el-row>
              <el-col :span="16">
                <el-form-item label="负责部门" prop="jjDeptId">
                  <el-select
                    v-model="dataForm.jjDeptId"
                    placeholder="请选择负责部门"
                    class="xiaLa"
                    style="width: 100%"
                    :clearable="true"
                    @change="switchDepartment"
                    :disabled="xgBz"
                  >
                    <el-option
                      v-for="(item, index) in fzbmData"
                      :key="index"
                      :label="item.deptName"
                      :value="item.deptId"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <div>
                  <el-form-item
                    label="允许无总额分配"
                    prop="sfNototal"
                    label-width="170px"
                  >
                    <template slot-scope="scope">
                      <el-radio :disabled="xgBz" v-model="dataForm.sfNototal" label="是"
                        >是</el-radio
                      >
                      <el-radio :disabled="xgBz" v-model="dataForm.sfNototal" label="否"
                        >否</el-radio
                      >
                    </template>
                  </el-form-item>
                </div>
              </el-col>
            </el-row>
            <!-- dataForm.sfCeff == '是' &&  -->
            <el-row
              v-if="dataForm.sfNototal == '否'"
            >
              <el-col
                :span="8"
                v-if="dataForm.sfCeff == '是' && dataForm.sfNototal == '否'"
              >
                <el-form-item label="超额发放率">
                  <el-input-number
                    v-model="dataForm.distrPerce"
                    placeholder="%"
                    style="width: 90%"
                    :min="1"
                    :max="100"
                    :disabled="xgBz"
                  >
                  </el-input-number
                  >%
                </el-form-item>
              </el-col>
              <el-col
                :span="8"
                v-if="dataForm.sfCeff == '是' && dataForm.sfNototal == '否'"
              >
                <el-form-item label="超额发放分类" prop="distrMe">
                  <el-select
                    v-model="dataForm.distrMe"
                    placeholder="请选择"
                    style="width: 100%"
                    :disabled="xgBz"
                  >
                    <el-option value="1" label="按总额"></el-option>
                    <el-option value="2" label="按月总额"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="dataForm.sfNototal == '否'">
                <el-form-item
                  label="允许超额发放"
                  prop="sfCeff"
                  label-width="170px"
                >
                  <el-radio :disabled="xgBz" v-model="dataForm.sfCeff" label="是">是</el-radio>
                  <el-radio :disabled="xgBz" v-model="dataForm.sfCeff" label="否">否</el-radio>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="奖金名称" prop="jjMc">
                  <el-input
                    v-model="dataForm.jjMc"
                    placeholder="奖金名称"
                    :disabled="xgBz"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="奖金类型" prop="jjLx">
                  <el-select
                    v-model="dataForm.jjLx"
                    placeholder="请选择"
                    :disabled="xgBz"
                    style="width: 100%"
                  >
                    <el-option value="1" label="年度"></el-option>
                    <el-option value="3" label="日常"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item
                  label="允许进入奖金池"
                  prop="sfPripool"
                  label-width="170px"
                >
                  <el-radio :disabled="xgBz" v-model="dataForm.sfPripool" label="是"
                    >是</el-radio
                  >
                  <el-radio :disabled="xgBz" v-model="dataForm.sfPripool" label="否"
                    >否</el-radio
                  >
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="开始日期" prop="jjDateq">
                  <el-date-picker
                    v-model="dataForm.jjDateq"
                    type="date"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    placeholder="开始日期"
                    :disabled="xgBz"
                    style="width: 100%"
                  ></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="结束日期" prop="jjDatez">
                  <el-date-picker
                    v-model="dataForm.jjDatez"
                    type="date"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    placeholder="结束日期"
                    style="width: 100%"
                    :disabled="xgBz"
                  ></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="dataForm.sfPripool == '是'">
                <el-form-item label="过期时间" prop="gqTime">
                  <el-date-picker
                    v-model="dataForm.gqTime"
                    type="date"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    placeholder="过期时间"
                    style="width: 100%"
                    :disabled="dataForm.sfPripool != '是'&&xgBz"
                  ></el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="分配来源" prop="fpLy">
                  <el-select
                    v-model="dataForm.fpLy"
                    placeholder="请选择"
                    style="width: 100%"
                    @change="followUpfp"
                    :disabled="xgBz"
                  >
                    <el-option value="1" label="单位自筹"></el-option>
                    <el-option value="2" label="上级分配"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="奖金总额" prop="jjZe">
                  <el-input-number
                    v-model="dataForm.jjZe"
                    @blur="isShu"
                    :min="0"
                    :max="1000000000"
                    :precision="2"
                    :step="1"
                    label="奖金总额"
                    style="width: 88%"
                    :disabled="dataForm.sfNototal == '是'||xgBz"
                  ></el-input-number>
                  元
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="奖金池" label-width="75px">
                  <el-select
                    v-model="dataForm.jjBh"
                    placeholder="请选择"
                    style="width: 100%"
                    :disabled="dataForm.fpLy == 2 ||xgBz"
                    @change="followUpjj"
                    multiple
                  >
                    <el-option
                      v-for="(item, j) in jjData"
                      :key="j"
                      :label="machining(item)"
                      :value="item.jjcId"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-col :span="8">
                <el-form-item label="上报日期">
                  <el-date-picker
                    v-model="dataForm.jjReportTime"
                    type="date"
                    value-format="yyyy-MM-dd"
                    placeholder="上报日期"
                    style="width: 100%"
                    :disabled="xgBz"
                  ></el-date-picker>
                </el-form-item>
              </el-col>
              </el-col>
            </el-row>
          </el-col>
          <el-col
            :span="4"
            style="
              display: flex;
              flex-direction: column;
              align-items: center;
              height: 200px;
              justify-content: space-around;
            "
          >
            <el-button v-if="!showForm.showFpid" style="width:100px;margin-left:10px;" :disabled="isDisable" @click="jiangjindaoru" type="primary">奖金导入</el-button>
            <el-upload
            v-else
            class="upload-demo"
            action="/admin/sys-file/upload"
            accept=".xls,.xlsx"
            :headers="headers"
            :before-upload="beforeFileUpload"
            :on-change="handleChange"
            :on-success="handleUploadSuccess"
            :show-file-list="false"
            :file-list="fileList"
            style="display: inline; margin-left: 10px; margin-right: 10px"
          >
            <el-button  size="small" style="width:100px;margin-left:10px;" type="primary">奖金导入</el-button>
          </el-upload>
            <el-button type="danger" style="width:100px;margin-left:10px;":disabled="showQing" @click="qingkong">导入清空</el-button>
            <el-button type="info"style="width:100px;margin-left:10px;" icon="el-icon-download" @click="daochu">模板导出</el-button>
            <el-button type="success"style="width:100px;margin-left:10px;" plain @click="showBtn">创建奖金项</el-button>
          </el-col>
        </el-row>
      </div>
      <el-row>
        <el-col :span="24">
<!--          :summary-method="getSummaries"-->
          <el-table
            :data="tableList.tableData"
            border
            stripe
            ref="table"

            show-summary
            min-height="50vh"
          >
            <el-table-column
              v-for="(ele, index) in tableList.tableColumn"
              :key="index"
              header-align="center"
              align="center"
              :prop="ele.prop"
              :label="ele.label"
            >
            </el-table-column>
          </el-table>
        </el-col>
        <el-col
          :span="24"
          style="border-bottom: 1px #028ae1 solid; margin: 20px 0"
        ></el-col>
      </el-row>
      <el-row
        v-for="(item, index) in dataForm.dataList"
        :key="index"
        v-if="listShows&&showFpjs"
      >
        <el-col :span="4">
          <el-form-item
            label-width="110px"
            label="奖金项名称"
            :prop="'dataList[' + index + '].jjxId'"
            :rules="[
              {
                required: true,
                message: '奖金项名称不能为空',
                trigger: 'blur',
              },
            ]"
          >
            <el-select
              v-model="dataForm.dataList[index].jjxId"
              clearable
              placeholder="请选择奖金项"
              :disabled="!isShowFpjs||dataForm.dataList[index].id!=''||dataForm.dataList[index].list.length>0"
              style="width: 100%"
              @change="jjxHandle(index)"
            >
              <el-option
                v-for="(itema,index) in cityHandle()"
                :key="index"
                :label="itema.jjxMc"
                :value="itema.id"
                :disabled="itema.disabled"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item
            label-width="110px"
            label="奖金项金额"
            :prop="'dataList[' + index + '].jjJe'"
            :rules="[
              {
                required: true,
                message: '奖金项金额不能为空',
                trigger: 'blur',
              },
            ]"
          >
            <el-input-number
              v-model="dataForm.dataList[index].jjJe"
              :disabled="!isShowFpjs"
              :min="0"
              :max="1000000000"
              :precision="2"
              :step="1"
              label="奖金项金额"
              style="width: 88%"
              @change="jjxZehj()"
            ></el-input-number>
            元
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item
            label-width="100px"
            label="机构分组"
            :prop="'dataList[' + index + '].fzId'"
            :rules="[
              {
                required: true,
                message: '机构分组不能为空',
                trigger: 'blur',
              },
            ]"
          >
            <el-select
              v-model="dataForm.dataList[index].fzId"
              :disabled="!isShowFpjs"
              clearable
              placeholder="请选择机构分组"
              style="width: 100%"
              @change="fenzuselect(dataForm.dataList[index].fzId, index)"
            >
              <el-option
                v-for="(itema,index) in jigouList"
                :key="index"
                :label="itema.jgFzName"
                :value="itema.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <!-- :prop="'dataList[' + index + '].gsId'":rules="[
              {
                required: true,
                message: '公式不能为空',
                trigger: 'blur',
              },
            ]" -->
          <el-form-item
            label-width="60px"
            label="公式"


          >
            <el-select
              v-model="dataForm.dataList[index].gsId"
              :disabled="!isShowFpjs"
              clearable
              placeholder="请选择公式"
              style="width: 100%"
              @change="gsselect(dataForm.dataList[index].gsId, index)"
            >
              <el-option
                v-for="(itema,index) in gsData"
                :key="index"
                :label="itema.gsMc"
                :value="itema.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item
            label-width="110px"
            label="奖金项日期"

            :prop="'dataList[' + index + '].jjxDate'"
            :rules="[
              {
                required: true,
                message: '奖金项日期不能为空',
                trigger: 'blur',
              },
            ]"
          >
            <el-date-picker
              v-model="dataForm.dataList[index].jjxDate"
              @change="jjxudpate(item)"
              :disabled="!isShowFpjs"
              type="date"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="奖金项日期"
              style="width: 100%"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <div>
            <el-form-item
              label-width="110px"
              label="是否专项奖"
              :prop="'dataList[' + index + '].sfZx'"
            >
              <el-radio-group v-model="dataForm.dataList[index].sfZx" :disabled="!isShowFpjs" @change="changesfZx">
                <el-radio label="是">是</el-radio>
                <el-radio label="否">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="1">
          <el-button
            @click="removeItem(index)"
            v-if="
              dataForm.dataList.length > 1 &&
              dataForm.dataList[index].id == '' &&
              dataForm.fpLy == 2
            "
            style="right: 5px"
            class="ml10"
            icon="el-icon-minus"
          ></el-button>
          <!--          v-if="-->
          <!--          index == dataForm.dataList.length - 1 &&-->
          <!--          dataForm.dataList[index].id == '' &&-->
          <!--          dataForm.fpLy == 2-->
          <!--          "-->
          <el-button
            @click="addItem()"
            v-if="!(dataForm.jjLx==1&&isJiangZ)&&isShowFpjs"
            icon="el-icon-plus"
            class="ml10"
          ></el-button>
        </el-col>
        <el-col :span="24" v-if="showFpjs" style="margin-bottom: 20px">
          <el-col :span="2" style="text-align: center">
            <el-button
              type="primary"
              icon="el-icon-arrow-up"
              circle
              v-if="item.shows"
              @click="item.shows = !item.shows"
            ></el-button>
            <el-button
              v-else
              type="primary"
              icon="el-icon-arrow-down"
              circle
              @click="item.shows = !item.shows"
            ></el-button>
          </el-col>
          <el-col :span="20">
            <el-table
              v-if="item.list.length > 0 && item.shows == true"
              :data="item.list"
              min-height="50vh"
              border
              stripe
            >
              <el-table-column
                header-align="center"
                align="center"
                prop="deptName"
                label="单位名称"
              >
              </el-table-column>
              <el-table-column
                header-align="center"
                align="center"
                prop="jjJe"
                :label="item.list[0].jjxMc"
              >
                <template slot-scope="scope">
                  <el-input
                    placeholder="请输入内容"
                    :min="1"
                    v-model="scope.row.jjJe"
                    type="Number"
                    @change="changeValue(scope.row)"
                  >
                  </el-input>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
          <el-col :span="2" style="text-align: center" v-if="item.shows">
            <el-button type="primary" v-if="isShowFpjs" @click="pfjsBtn(item, index)"
              >分配计算</el-button
            >
          </el-col>
        </el-col>
      </el-row>
    </el-form>
    <span style="position: fixed; bottom: 20px; right: 20px">
      <el-button type="primary" plain @click="close">取消</el-button>
      <el-button type="primary" plain @click="tsJjfp()">提交审核</el-button>
      <el-button v-if="showFileBtn" type="primary" plain @click="fjgl">附件管理</el-button>
      <el-button type="primary" plain @click="close">确认</el-button>
      <!-- <el-button type="primary" @click="dataFormSubmit()" v-if="canSubmit"
        >确定</el-button
      > -->
    </span>
    <!--提交审核选人-->
    <personCard
        ref="usercomment"
        :isJjfp="true"
        @submitfy="submitfy"
      ></personCard>
      <!--附件管理-->
      <jiangjinfpjjfpdjbFileManager
        ref="jiangjinfpjjfpdjbFileManager"
      ></jiangjinfpjjfpdjbFileManager>
  </el-dialog>
</template>

<script>
import {
  addObj,
  getObj,
  updateById,
  updateBmFP4init,
  updateBmFP4Jjx,
  sendFP,
  deleteJiangjinByimport,
  getJiangjinDataByImport,
  getFzGsData
} from "@/api/jiangjin/jiangjinfpjjfpdjb";
import { getFplyList } from "@/api/jiangjin/jiangjinfpjjlydjb";
import { getJjDeptJjx, getJjxByjjxfl } from "@/api/jiangjin/jiangjinjjxxxb";
import { getJiangJinBm } from "@/api/admin/dept";
import { getJgfzList } from "@/api/jiangjin/jiangjinryfzb";
import { getJjDeptJjgtoPrant } from "@/api/admin/sysformula";
import { getStore } from "@/util/store";
import store from "@/store";
  import request from '@/router/axios'
import personCard  from "@/views/jiangjin/jiangjinfpjjfpdjb/xincaozuo/personCard";
import jiangjinfpjjfpdjbFileManager from "./jiangjinfpjjfpdjb-file-manager";
export default {
  components: {
    personCard,
    jiangjinfpjjfpdjbFileManager
    },
  data() {
    return {
      xgBz: false,
      visible: false,
      canSubmit: false,
      cityOptions: [],
      jjData: [], //奖金池
      jjxList: [], //奖金项list
      fzbmData: [],
      headers: {
        'TENANT-ID': getStore({ name: "tenantId" })
              ? getStore({ name: "tenantId" })
              : "1",
        Authorization: "Bearer " + store.getters.access_token,
      },
      totalData: [
        {
          name: "吉林业务部",
          amount1: "234",
          amount2: "3.2",
          amount3: "10",
        },
        {
          name: "天津业务部",
          amount1: "165",
          amount2: "4.43",
          amount3: "12",
        },
      ],
      dataForm: {
        id: 0,
        jjDeptId: "",
        jjDeptName: "",
        sfZx: "",
        sfCeff: "",
        jjLx: "",
        fpLy: "",
        gqTime: new Date(new Date().getFullYear() + "-12-31 23:59:59"),
        jjBh: "",
        jjMc: "",
        jjDateq: "",
        jjDatez: "",
        jjZe: "",
        dataList: [],
        jjZelin: 0,
        isShuCheck: false,
        sfNototal: "否",
        sfPripool: "",
        distrPerce: 1,
        distrMe: "",
        jjReportTime:""
      },
      isRef: false,
      dataRule: {
        jjDeptId: [
          { required: true, message: "请选择负责部门", trigger: "blur" },
        ],
        sfNototal: [
          {
            required: true,
            message: "是否允许无总额分配不能为空",
            trigger: "blur",
          },
        ],
        sfCeff: [
          {
            required: true,
            message: "是否允许超额发放不能为空",
            trigger: "blur",
          },
        ],
        // distrPerce:[
        //   {required: true, message: '超额发放百分比不能为空', trigger: 'blur'}
        // ],
        distrMe: [
          { required: true, message: "超额发放分类不能为空", trigger: "blur" },
        ],
        sfZx: [
          { required: true, message: "是否允许预留不能为空", trigger: "blur" },
        ],
        jjLx: [{ required: true, message: "请选择奖金类型", trigger: "blur" }],
        fpLy: [{ required: true, message: "请选择分配来源", trigger: "blur" }],
        gqTime: [
          { required: true, message: "过期时间不能为空", trigger: "blur" },
        ],
        jjBh: [{ required: true, message: "请选择奖金池", trigger: "blur" }],
        jjMc: [
          { required: true, message: "奖金名称不能为空", trigger: "blur" },
        ],
        jjDateq: [
          { required: true, message: "开始日期不能为空", trigger: "blur" },
        ],
        jjDatez: [
          { required: true, message: "结束日期不能为空", trigger: "blur" },
        ],
      },
      isJiangZ: false,
      isAdd: true,
      jjcZye: 0,
      deptId: 1,
      jigouList: [],
      gsData: [],
      fpId: "",
      tableList: {
        tableData :[],
      },
      listShows: false,
      showsubmit:true,
      fileList:[],
      bLoading:false,
      showForm:{
        showFpid:false
      },
      showFpjs:true,
      isShowFpjs:true,
      isDisable:false,
      showQing:true,
      showFileBtn:false,
      jjDataTwo:[]
    };
  },
  watch: {
    "dataForm.sfZx": {
      handler(newName, oldName) {
        console.log(newName, oldName);
        if (newName == "否") {
          this.dataForm.gqTime = new Date(
            new Date().getFullYear() + "-12-31 23:59:59"
          );
        }
      },
      immediate: true,
      // deep: true
    },
  },
  methods: {
    //附件管理
    fjgl() {
      if(this.fpId){
          this.$nextTick(() => {
          this.$refs.jiangjinfpjjfpdjbFileManager.init(this.fpId);
        });
      }else{
        this.$message.closeAll()
        this.$message.warning('请先添加奖金项!')
      }

    },
    //点击奖金项名称进入
    xiangqing(rowid){
      this.fpId=rowid
      this.visible=true
      getJiangjinDataByImport(this.fpId).then(res=>{
        this.dataForm=res.data.data.jiangjinDatas
        this.dataForm.dataList=res.data.data.listjj
        this.tableList.tableColumn=res.data.data.tableColumn
        this.tableList.tableData=res.data.data.tableData
        getJjDeptJjx(this.dataForm.jjDeptId).then((res) => {
          this.cityOptions = res.data.data;
        });
        this.xgBz = true; //表单不可编辑
        this.listShows = true;
          this.showFpjs=true   //是否显示奖金项一行数据及详情table
          this.showsubmit=true
          this.isDisable=true   //导入成功之后不让点导入奖金
          this.isShowFpjs=false; //是否显示分配计算按钮以及奖金项一行数据是否可编辑
          this.showQing=false  //清空按钮可点击
      })
    },
    //分配提审
    tsJjfp() {
      if(this.fpId){
        this.$nextTick(() => {
          this.$refs.usercomment.init("12", "allTree", "", "htcj",'提交审核');
        });
      }else{
        this.$message.closeAll()
        this.$message.warning('请先添加奖金项')
      }

    },
    submitfy(data) {

      var ids = "";
      data.tableDataUser.forEach((ele) => {
        ids = ids + ele.userId + ",";
      });

      var params = {
        fpId: this.fpId,
        userList: ids,
        pd:data.formRen.isFs,
        asssj:data.formRen.userId,
      };

      sendFP(params).then((res) => {
        this.$message.closeAll()
          this.$message.success("提交审核成功");
          this.close()
        });
      // data.tableDataUser;
    },
    jiangjindaoru(){
      this.$message.closeAll()
      this.$message.warning("请先点击创建奖金项!")
    },
    beforeFileUpload(file) {
      ////console.log(file);
      const cType = file.type;
      let isXls = false;

      // const isXls = file.type === 'xls/xlsx';
      if (
        cType === "application/vnd.ms-excel" ||
        cType ===
          "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
      ) {
        isXls = true;
      }

      if (!isXls) {
        this.$message.closeAll()
        this.$message.error("导入文件只能是 Excel 格式!");
      }
      return isXls;
    },
    qingkong(){
      deleteJiangjinByimport(this.fpId).then(res=>{
        this.$message.closeAll()
        this.$message.success('清空成功!')
        this.dataForm.dataList=[]
        this.tableList.tableData=[]
        this.tableList.tableColumn=[]
        this.showQing=true
        this.isDisable=false
        this.$set(this.showForm,'showFpid',true)
      })
    },
    handleChange(file, fileList) {
      this.fileList = [];
      this.fileList.push(file);
    },
    handleUploadSuccess(response, file, fileList) {
      ////console.log('3232323')  show-overflow-tooltip
      this.showExist = true;

      if (response.code !== 0) {
        this.$message.closeAll()
        this.$message.error("上传出错：" + response.msg);
        return;
      }

      this.bLoading = true;

      request({
        url:
          "/jiangjin//jiangjinfpjjfpdjb/importJiangjin/" +
          response.data.bucketName +
          "/" +
          response.data.fileName +
          "/" +
          this.fpId,
        method: "get",
      })
        .then((res) => {
          // this.tableImpExcel = [];
          // this.tableImpExcel = res.data.data;
          // this.getDataList();
          this.tableList.tableData = res.data.data.tableData;
          this.tableList.tableColumn = res.data.data.tableColumn;
          this.dataForm.dataList=res.data.data.listjj;
          this.$set(this.dataForm,'jjZe',res.data.data.jjzeData)
          this.showFpjs=true   //是否显示奖金项一行数据及详情table
          this.showsubmit=true
          this.bLoading = false;
          this.isDisable=true   //导入成功之后不让点导入奖金
          this.isShowFpjs=false; //是否显示分配计算按钮以及奖金项一行数据是否可编辑
          this.showQing=false  //清空按钮可点击
          this.$set(this.showForm,'showFpid',false)
          this.$message.closeAll();
          this.$message.success("导入成功!");

        })
        .catch((error) => {
          this.bLoading = false;
          this.$message.closeAll();
          this.$message.error("导入模板中数据存在异常!");
           this.isDisable=false
        });
    },
    daochu(){
        if(!this.fpId){
          this.$message.warning('添加完奖金项之后才可以导出!')
          return false
        }
        return request({
          url: '/jiangjin/jiangjinFqmxb/downloadMB/'+this.fpId,
          method: 'post',
          responseType: 'arraybuffer'
        }).then((response) => { // 处理返回的文件流
          const blob = new Blob([response.data], {
            type: 'application/vnd.ms-excel'
          })
          const link = document.createElement('a')
          link.href = URL.createObjectURL(blob)
          link.download = '奖金模板.xlsx'
          document.body.appendChild(link)
          link.click()
          window.setTimeout(function () {
            URL.revokeObjectURL(blob)
            document.body.removeChild(link)
          }, 0)
        })
    },
    changesfZx(val){
      var list=[];
      this.dataForm.dataList.forEach(item=>{
        if(item.sfZx=='是'){
          list.push(item)
        }
      })
      console.log(list.length)
      if(list.length>0){
        this.isJiangZ=true
      }else{
        this.isJiangZ=false
      }

    },
    showBtn() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.listShows = true;
          // 保存生成分配id
          var data = {
            fpxx: JSON.stringify(this.dataForm),
            lysyxx: [],
          };
          addObj(data).then((res) => {
            this.fpId = res.data.data;
           this.$set(this.showForm,'showFpid',true)
           this.$nextTick(()=>{
             this.$forceUpdate()
           })

          });
          this.showsubmit = false;
        }
      });
    },
    // 分配计算
    pfjsBtn(item, index) {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          var list = [];
          var obj = {};
          this.dataForm.dataList.forEach((ele) => {
            list.push({
              jjxId: ele.jjxId,
              jjxName: ele.jjxMc,
              jjxDate: ele.jjxDate,
            });
            obj[ele.jjxId] = {
              bmJj: ele.jjJe,
              jjZe: ele.jjJe,
              fpJj: ele.jjJe,
              dxFp: 0,
              ygJj: 0,
              zjJj: 0,
              jjYe: 0,
            };
          });
          console.log(JSON.stringify(item));
          var params = {
            fpId: this.fpId,
            jjZe: this.dataForm.jjZe,
            jjxId: item.jjxId,
            jjxMc: item.jjxMc,
            fzId: item.fzId,
            fzName: item.fzName,
            gsId: item.gsId?item.gsId:"-1",
            gsName: item.gsName,
            jjJe: item.jjJe,
            jjxDate: item.jjxDate,
            sfZx: item.sfZx,
            jjxXq: JSON.stringify(list),
            jjxlist:JSON.stringify(this.jjDataTwo),
            jjxJeXq: obj,
            fply:this.dataForm.fpLy,
            jjcId: this.dataForm.jjBh
          };
          if(!this.fpId){
            this.$message.closeAll()
            this.$message.warning("请先点击添加奖金项！")
            return false
          }
          updateBmFP4init(params).then((res) => {
            this.tableList = res.data.data;
            this.dataForm.dataList[index].list = res.data.data.list;
            this.showFileBtn=true //显示附件管理按钮
            //this.isDisable=true
          });
        }
      });
      this.showsubmit = true;
    },
    changeValue(row) {
      console.log(row);
      var params = {
        id: row.id,
        jjJe: row.jjJe,
        fpId: this.fpId,
      };
      updateBmFP4Jjx(params).then((res) => {
        this.tableList.tableData = res.data.data.tableData;
        this.tableList.tableColumn = res.data.data.tableColumn;
        var list=res.data.data.listjj;
        list.forEach(item=>{
          this.dataForm.dataList.forEach(it=>{
            if(item.jjxId==it.jjxId){
              item.sfZx=it.sfZx
            }else{
              item.sfZx='否'
            }
          })
        })
        this.dataForm.dataList=list
        this.dataForm.dataList.forEach((item,index)=>{
          this.jjxHandle(index)
        })
        this.$set(this.dataForm,'jjZe',res.data.data.jjzeData)
        this.$forceUpdate()
      });
    },
    // 总计表统计 tableData tableColumn
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "总计";
          return;
        }

        const values = data.map((item) => Number(item[column.property]));
        if (!values.every((value) => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          if (index === 1) {
            sums[index] += "人";
          } else {
            sums[index] += " 元";
          }
        } else {
          sums[index] = "N/A";
        }
      });
       let num=sums.toFixed(2)
      return num;
    },
    getjgfz(jjDeptId) {
      getJgfzList(jjDeptId).then((res) => {
        this.jigouList = res.data.data;
      });
    },
    getGongshi(deptId) {
      getJjDeptJjgtoPrant({
        id: deptId,
        getJJxNamegsType: "奖金算法",
        gsType: "奖金算法",
        gsFl: "部门",
      }).then((res) => {
        this.gsData = res.data.data;
      });
    },
    //是否点击了金额输入框
    isShu() {
      this.isShuCheck = true;
    },
    fenzuselect(val, index) {
      var params = this.jigouList.find((ele) => ele.id == val);

      this.dataForm.dataList[index].fzName = params.jgFzName;
      console.log(this.dataForm.dataList[index]);
      this.$forceUpdate()
    },
    gsselect(val, index) {
      console.log(val);
      var params = this.gsData.find((ele) => ele.id == val);

      this.dataForm.dataList[index].gsName = params.gsMc;
      console.log(this.dataForm.dataList[index]);
      this.$forceUpdate()
    },
    //奖金项总额合计
    jjxZehj(){
      this.dataForm.dataList.forEach(item=>{
       if(this.jjDataTwo.length>0){
         this.jjDataTwo.forEach(it=>{
           console.log(JSON.stringify(item))
           console.log(JSON.stringify(it))
          if(item.id==it.id){
            if(item.jjJe*1>item.jjcYe*1){
              console.log(JSON.stringify(item))
              this.$message.closeAll()
              this.$message.warning("输入的金额不能大于奖金池的金额!")
              console.log(JSON.stringify(item))
              this.$set(item,'jjJe',item.jjcYe)
              this.isRef = !this.isRef;
              this.$forceUpdate()
            }
          }else{
            this.jiSuanZe()
          }
        })
       }else{
         this.jiSuanZe()
       }

      })

    },
    jiSuanZe(){
      if (this.dataForm.sfNototal == "否") {
        this.dataForm.jjZelin = 0;
        var zongE = 0;
        for (var a in this.dataForm.dataList) {
          this.dataForm.jjZelin =
            this.dataForm.jjZelin +
            (this.dataForm.dataList[a].jjJe == undefined
              ? 0
              : this.dataForm.dataList[a].jjJe);

          if (
            this.dataForm.sfCeff == "是" &&
            this.dataForm.distrPerce * 1 > 0
          ) {
            zongE =
              (this.dataForm.jjZe * 1 + this.jjcZye * 1) *
              (1*1 + (this.dataForm.distrPerce * 1) / 100);

            if (this.dataForm.jjZelin * 1 > zongE) {
              this.dataForm.dataList[a].jjJe = 0;
              this.$message.closeAll()
              this.$message.warning("奖金项金额总和大于奖金总额");
              //console.log(this.dataForm.dataList[a].jjJe)
              this.isRef = !this.isRef;
              this.$forceUpdate();
            }
          }
          if (
            this.dataForm.sfCeff == "是" &&
            this.dataForm.distrPerce * 1 == 0
          ) {
            this.dataForm.jjZe = 0;
            this.dataForm.jjZe =
              this.dataForm.jjZe*1 +
              (this.dataForm.dataList[a].jjJe == undefined
                ? 0
                : this.dataForm.dataList[a].jjJe*1);
          }
          if (this.dataForm.sfCeff == "否") {
            if (
              this.dataForm.jjZelin * 1 >
              this.dataForm.jjZe * 1 + this.jjcZye * 1
            ) {
              this.dataForm.dataList[a].jjJe = 0;
              this.$message.closeAll()
              this.$message.warning("奖金项金额总和大于奖金总额");
              //console.log(this.dataForm.dataList[a].jjJe)
              this.isRef = !this.isRef;
              this.$forceUpdate();
            }
          }
        }
      } else {
        this.dataForm.jjZe = 0;
        for (var a in this.dataForm.dataList) {

          this.dataForm.jjZe =
            this.dataForm.jjZe*1 +
            (this.dataForm.dataList[a].jjJe == undefined
              ? 0
              : this.dataForm.dataList[a].jjJe*1);
        }
      }
    },
    //奖金项数据处理
    jjxHandle(index) {
      for (var a in this.cityOptions) {
        if (this.cityOptions[a].id == this.dataForm.dataList[index].jjxId) {
          this.dataForm.dataList[index].jjxMc = this.cityOptions[a].jjxMc;
          this.fngetFzGsData(this.dataForm.dataList[index].jjxId,index)
          break;
        }
      }
    },
    fngetFzGsData(jjxid,index){
      getFzGsData(jjxid,this.deptId).then(res=>{
        this.$message.closeAll()
        if(res.data.data){
          this.$set(this.dataForm.dataList[index],'fzId',res.data.data.fzId)
          this.$set(this.dataForm.dataList[index],'gsId',res.data.data.gsId)
        }
        if(res.data.msg){
          this.$message.warning(res.data.msg)
        }
      })
    },
    //奖金项下拉处理
    cityHandle() {
      for (var b in this.cityOptions) {
        this.cityOptions[b].disabled = false;
        for (var a in this.dataForm.dataList) {
          if (this.dataForm.dataList[a].jjxId == this.cityOptions[b].id) {
            this.cityOptions[b].disabled = true;
          }
        }
      }

      return this.cityOptions;
    },
    //奖金点击事件
    followUpjj(value) {
      console.log("value:"+JSON.stringify(value))
      console.log("jjData:"+JSON.stringify(this.jjData))
      this.jjxList = [];
      this.dataForm.dataList = [];
      this.jjcZye = 0;
      for (var a in value) {
        for (var b in this.jjData) {
          if (value[a] == this.jjData[b].jjcId) {
            this.jjxList.push({
              id: this.jjData[b].jjcId,
              jjxId: this.jjData[b].jjxId,
              jjxMc: this.jjData[b].jjxName,
              jjJe: this.jjData[b].jjcYe,
              jjxDate: "",
              sfZx: "否",
            });
            this.jjcZye = this.jjcZye * 1 + this.jjData[b].jjcYe * 1;
          }
        }
      }

      var map = new Map();
      for (var c in this.jjxList) {
        if (!map.has(this.jjxList[c].jjxId)) {
          map.set(this.jjxList[c].jjxId, {
            id: this.jjxList[c].id,
            jjxId: this.jjxList[c].jjxId,
            jjxMc: this.jjxList[c].jjxMc,
            jjJe: this.jjxList[c].jjJe,
            jjxDate: "",
            sfZx: this.jjxList[c].sfZx,
            shows: true,
      gsId: "",
      fzId: "",
      fzName: "",
      gsName: "",
      list: [],
            jjcYe:this.jjxList[c].jjJe
          });
        } else {
          var jjcYe = map.get(this.jjxList[c].jjxId).jjJe;
          map.set(this.jjxList[c].jjxId, {
            id: this.jjxList[c].id,
            jjxId: this.jjxList[c].jjxId,
            jjxMc: this.jjxList[c].jjxMc,
            jjJe: this.jjxList[c].jjJe + jjcYe,
            jjxDate: "",
            sfZx: this.jjxList[c].sfZx,
            shows: true,
            gsId: "",
            fzId: "",
            fzName: "",
            gsName: "",
            list: [],
            jjcYe:this.jjxList[c].jjJe + jjcYe
          });
        }
      }
      getJjxByjjxfl({ id: this.deptId, jjxfl: "4080奖" }).then((res) => {
        this.cityOptions = res.data.data;
      });
  //     this.dataForm.dataList=this.jjxList.map(item=>{
  //           item.jjxDate= ""
  //           item.shows=true
  //           item.gsId= ""
  //           item.fzId= ""
  //           item.fzName= ""
  //           item.gsName= ""
  //           item.list= []
  //           return item
  //     })
      this.dataForm.dataList = [...map.values()];
      this.jjDataTwo = [...map.values()]; //计算金额时对比用
     // console.log("this.dataForm.dataList:"+JSON.stringify(this.dataForm.dataList))
      //this.listShows=true
     //this.showFpjs=true
      this.jjxZehj();
    },
    //奖金项日期批量修改
    jjxudpate(item) {
      for (var a in this.jjxList) {
        if (this.jjxList[a].jjxId == item.jjxId) {
          this.jjxList[a].jjxDate = item.jjxDate;
        }
      }
    },
    //奖金池下拉name数据加工
    machining(item) {
      return item.jjxName + "-" + item.jjxFl + "(" + item.jjcYe + "元)";
    },
    //分配点击事件
    followUpfp(value) {
      console.log(value);
      //1奖金池 2单位自筹
      this.dataForm.jjZe = 0;
      this.dataForm.jjBh = "";
      this.dataForm.dataList = [
        {
          jjxId: "",
          jjxMc: "",
          jjJe: 0,
          jjxDate: "",
          sfZx: "否",
          id: "",
          shows: true,
          gsId: "",
          fzId: "",
          fzName: "",
          gsName: "",
          list: [],
        },
      ];
      if (value == "2") {
        getJjDeptJjx(this.deptId).then((res) => {
          this.cityOptions = res.data.data;
        });
      }
    },
    //添加数据项
    addItem() {
      this.dataForm.dataList.push({
        jjxId: "",
        jjxMc: "",
        jjJe: 0,
        jjxRq: "",
        sfZx: "否",
        id: "",
        shows: true,
        gsId: "",
        fzId: "",
        fzName: "",
        gsName: "",
        list: [],
      });
    },
    //移除数据项
    removeItem(index) {
      this.dataForm.dataList.splice(index, 1);
      this.jjxZehj();
    },
    //初始化
    csh() {
      this.xgBz = false;
      this.jjxList = [];
      this.jjData = [];
      this.cityOptions = [];
      this.isShuCheck = false;
      this.showFpjs=true  //是否显示奖金项一行数据及详情table
      this.isDisable=false //导入成功之后不让点导入奖金
      this.showsubmit=true
      this.showQing=true  //清空按钮不可点击
      this.isShowFpjs=true; //是否显示分配计算按钮以及奖金项一行数据是否可编辑
      this.$set(this.showForm,'showFpid',false)

      this.dataForm = {
        id: 0,
        jjDeptId: "",
        jjDeptName: "",
        sfZx: "否",
        sfCeff: "否",
        jjLx: "",
        fpLy: "",
        gqTime: new Date(new Date().getFullYear() + "-12-31 23:59:59"),
        jjBh: "",
        jjMc: "",
        jjDateq: "",
        jjDatez: "",
        jjZe: 0,
        dataList: [],
        jjZelin: 0,
        sfNototal: "否",
        sfPripool: "否",
        distrPerce: "",
        distrMe: "",
        deptId: 1,
        jjReportTime:""
      };
    },
    init(id, text) {
      this.tableList = [];
      this.showsubmit = true
      this.listShows = false,
      this.showFileBtn=false
      this.deptId = 1;
      this.csh();
      this.dataForm.id = id || 0;
      if (text == "新增") {
        this.dataRule.jjBh[0].required = true;
      } else {
        this.dataRule.jjBh[0].required = false;
      }

      this.visible = true;
      this.canSubmit = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
        getJiangJinBm().then((res) => {
          if (res.data.data.length > 0) {
            this.fzbmData = res.data.data;
          }
        });
        getFplyList(0).then((response) => {
          this.jjData = response.data.data;
        });
        if (this.dataForm.id) {
          getObj(this.dataForm.id).then((res) => {
            this.xgBz = true;
            this.dataForm = res.data.data;
            this.dataForm.jjLx = this.dataForm.jjLx + "";
            this.dataForm.fpLy = this.dataForm.fpLy + "";

            var jjxXq = JSON.parse(this.dataForm.jjxXq);
            //var jjxJeXq = JSON.parse(this.dataForm.jjxJeXq);
            var detailJson = JSON.parse(this.dataForm.detailJson);
            this.$set(this.dataForm, "dataList", []);

            for (var a in detailJson) {
              this.dataForm.dataList.push({
                jjxId: detailJson[a].jjxId,
                jjxMc: detailJson[a].jjxName,
                jjJe: detailJson[a].jjxJe,
                jjxRq: detailJson[a].jjxDate,
                sfZx: detailJson[a].sfZx,
                id: detailJson[a].id,
              });
            }
            getJjDeptJjx(this.dataForm.jjDeptId).then((res) => {
              this.cityOptions = res.data.data;
            });

            for (var a in this.fzbmData) {
              if (this.fzbmData[a].deptId == this.dataForm.jjDeptId) {
                this.dataForm.jjDeptId = this.fzbmData[a].deptId;
                this.dataForm.jjDeptName = this.fzbmData[a].deptName;
              }
            }
          });
        }
      });
    },
    switchDepartment(deptId) {
      this.deptId = deptId;
      this.getjgfz(this.deptId);
      this.getGongshi(this.deptId);
      this.csh();
      if (deptId != "") {
        getFplyList(deptId, 0).then((response) => {
          this.jjData = response.data.data;
          //console.log(JSON.stringify(response))
        });

        getJjDeptJjx(deptId).then((res) => {
          this.cityOptions = res.data.data;
        });

        for (var a in this.fzbmData) {
          if (this.fzbmData[a].deptId == deptId) {
            this.dataForm.jjDeptId = this.fzbmData[a].deptId;
            this.dataForm.jjDeptName = this.fzbmData[a].deptName;
          }
        }
      }
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          //结束大于等于开始
          if (this.dataForm.jjDatez < this.dataForm.jjDateq) {
            this.$notify.closeAll();
            this.$notify.error("结束时间应大于开始时间。");
            return;
          }

          // 过期大于结束
          if (this.dataForm.gqTime <= this.dataForm.jjDatez) {
            this.$notify.closeAll();
            this.$notify.error("过期时间应大于结束时间。");
            return;
          }

          var jjxXq = [];
          var jjxJeXq = {};
          for (var a in this.dataForm.dataList) {
            jjxXq.push({
              jjxId: this.dataForm.dataList[a].jjxId,
              jjxName: this.dataForm.dataList[a].jjxMc,
              jjxDate: this.dataForm.dataList[a].jjxRq,
              sfZx: this.dataForm.dataList[a].sfZx,
              id: this.dataForm.dataList[a].id,
            });

            this.$set(jjxJeXq, this.dataForm.dataList[a].jjxId, {
              fpJj: this.dataForm.dataList[a].jjJe,
              zjJj: 0,
              jjZe: this.dataForm.dataList[a].jjJe,
              bmJj: 0,
              ygJj: 0,
              dxFp: 0,
              jjYe: this.dataForm.dataList[a].jjJe,
              sfZx: this.dataForm.dataList[a].sfZx,
              id: this.dataForm.dataList[a].id,
            });
            // if(this.dataForm.dataList[a].gsId){
            //   this.dataForm.dataList[a].gsId="-1"
            // }
          }

          this.dataForm.jjxXq = JSON.stringify(jjxXq);
          this.dataForm.jjxJeXq = JSON.stringify(jjxJeXq);

          var data = {};
          if (this.dataForm.fpLy == "1") {
            //奖金池
            data = {
              fpxx: JSON.stringify(this.dataForm),
              lysyxx: JSON.stringify(this.jjxList),
            };
          } else if (this.dataForm.fpLy == "2") {
            //单位自筹
            data = {
              fpxx: JSON.stringify(this.dataForm),
              lysyxx: JSON.stringify(this.dataForm.dataList),
            };
          }

          this.canSubmit = false;
          if (this.dataForm.id) {
            updateById(data)
              .then((res) => {
                this.$notify.closeAll();
                this.$notify.success("修改成功");
                this.close();
                this.$emit("refreshDataList");
              })
              .catch(() => {
                this.canSubmit = true;
              });
          } else {
            addObj(data)
              .then((res) => {
                this.$notify.closeAll();
                this.$notify.success("添加成功");
                this.close();
                this.$emit("refreshDataList");
              })
              .catch(() => {
                this.canSubmit = true;
              });
          }
        }
      });
    },
    close() {
      this.$message.closeAll()
      if(this.showsubmit){
        this.visible = false;
        this.showFileBtn=false
        this.csh();
        this.$emit("refreshDataList");
      }else{
        this.$message.warning('请完成当前机构奖金分配')
      }

    },
  },
};
</script>
<style scoped>
.el-divider {
  background-color: #fff;
}
</style>
<style>
.totalData .el-table__footer-wrapper .has-gutter tr td {
  color: red;
}
</style>
